//
//  CZOauthViewController.swift
//  sinaWeiboswift
//
//  Created by 段文杰 on 16/4/10.
//  Copyright © 2016年 段文杰. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking

class CZOauthViewController: UIViewController,UIWebViewDelegate {

    
    override func loadView() {
        
        view = webView
        
        webView.delegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
       view.backgroundColor=UIColor.init(red: ( CGFloat(arc4random_uniform(256)) / 255.0), green: ( CGFloat(arc4random_uniform(256)) / 255.0), blue: ( CGFloat(arc4random_uniform(256)) / 255.0), alpha: 1.0)
        print(webView)

        //加载网络请求
        let url = oauthURL()
        
        let request = NSURLRequest(URL: url)
        
        webView.loadRequest(request)
        
        
        //设置延时效果
        SVProgressHUD.showWithStatus("正在加载中>>>>>>>>")
        SVProgressHUD.setDefaultMaskType(.None)
        
        
        setUI()
        
    }
    
    
    
    

    // MARK: - ******************* 设置OAuthVCUI以及点击方法 ********************
    func setUI () {
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: .Plain, target: self, action:  #selector(TianBtnDidClick))
        self.navigationItem.leftBarButtonItem?.setTitleTextAttributes([NSForegroundColorAttributeName : UIColor.init(red: ( CGFloat(arc4random_uniform(256)) / 255.0), green: ( CGFloat(arc4random_uniform(256)) / 255.0), blue: ( CGFloat(arc4random_uniform(256)) / 255.0), alpha: 1.0)], forState: .Normal)
        
        self.view.backgroundColor = UIColor.init(red: ( CGFloat(arc4random_uniform(256)) / 255.0), green: ( CGFloat(arc4random_uniform(256)) / 255.0), blue: ( CGFloat(arc4random_uniform(256)) / 255.0), alpha: 1.0)
        
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: .Plain, target: self, action:  #selector(MissBtnDidClick))
        self.navigationItem.rightBarButtonItem?.setTitleTextAttributes([NSForegroundColorAttributeName : UIColor.init(red: ( CGFloat(arc4random_uniform(256)) / 255.0), green: ( CGFloat(arc4random_uniform(256)) / 255.0), blue: ( CGFloat(arc4random_uniform(256)) / 255.0), alpha: 1.0)], forState: .Normal)
        
        self.view.backgroundColor = UIColor.init(red: ( CGFloat(arc4random_uniform(256)) / 255.0), green: ( CGFloat(arc4random_uniform(256)) / 255.0), blue: ( CGFloat(arc4random_uniform(256)) / 255.0), alpha: 1.0)
    
    }
    
    //设置URL方法
    func oauthURL() -> NSURL {
        let urlstr = OauthUrl + "?client_id=" + client_id + "&redirect_uri=" + redirect_uri
    return NSURL(string: urlstr)!
    
    }
   @objc func TianBtnDidClick () {
    print("填充点击了")
    // 使用webView执行js代码
    let js = "document.getElementById('userId').value = 'czbkiosweibo@163.com';document.getElementById('passwd').value = 'czbkios999'"
//    let js = "document.getElementById('userId').value = '13286834781';document.getElementById('passwd').value = 'dwg4910951'"

    webView.stringByEvaluatingJavaScriptFromString(js)
    }
    @objc func MissBtnDidClick() {
    
    print("取消点击了")
        self.dismissViewControllerAnimated(true, completion: nil)
    }
    
    
    
    // MARK: - ******************* webView代理方法 ********************
    
//  extension CZOauthViewController: UIWebViewDelegate {
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        let urlStr = request.URL?.absoluteString
        
        let isRsddirectURLSTR = urlStr?.hasPrefix(redirect_uri)
        
        if !isRsddirectURLSTR! {
            return true
        }else{
    
            print(request)
        
            let codestr: String = "code="
            
            let query = request.URL?.query
            
        
            
            if query!.hasPrefix(codestr) {
                print("授权按钮点击了")
                //将{ URL: http://www.baidu.com/?code=0ec047ca7227bc93a06113f45879c3f2 }code后面的字符串转换成nsstring类型 后面AFNetworking 要用到
//                let code = (query! as NSString).substringToIndex(codestr.characters.count)
                let code = (query! as NSString).substringFromIndex(codestr.characters.count)
                print(code)
                
          

                

                //TODO:好烦躁这个蓝鸟东西
                
                CZUseraccountViewModel.sharInatance.loaderAcceseeToken(code, callBack: { (error) in
                    if error != nil {
                        HMPrint("加载accessToken出错了: \(error)")
                        SVProgressHUD.showErrorWithStatus("网络不给力")
                        
                        // 延时关闭
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
                            self.MissBtnDidClick()
                        })
                        return
                    }
                    
                    // 成功了
                    HMPrint("加载AccessToken成功了")
                    self.MissBtnDidClick()
                    //切换界面到欢迎界面
                    (UIApplication.sharedApplication().delegate as!AppDelegate).switchViewcontroller(HMWelcomeViewController())
                    
                    
                })
            }
            
            else{
                print("点击了微博VIew取消按钮")
            MissBtnDidClick()
            
            }
            return false
        }
        
        
        
        
    }
    
    
        @objc  func webViewDidFinishLoad(webView: UIWebView) {
            SVProgressHUD.dismiss()
        }
        
        @objc func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
            HMPrint("error: \(error)")

            if error?.code == 102 {
                // 点击取消,加载被中断
                return
            }

            SVProgressHUD.showErrorWithStatus("加载失败!网络太不给力了>>>")
            SVProgressHUD.setDefaultMaskType(.None
            )
        }

   
    
    
    // MARK: - ******************* 懒加载数webView ********************
    
    lazy var webView : UIWebView = UIWebView()

    
    
    
}
